"use strict";

var path = require('path'),
    C = require('../common'),
    fs = C.fs,
    S = C.S;

module.exports = function (webModule, route, options, cb){
    options = options || {};

    if (!options.root) {
        return cb('"root" option is required!');
    }

    var root = webModule.toAbsPath(options.root);

    cb(null, function (req, res, next) {
        var filename;

        if (req.params.length > 0) {
            filename = req.params[0];
            if (!filename) {
                throw new C.Error.UsageError();
            }
        } else {
            filename = path.relative(webModule.route, req.path);
        }

        if (S(filename).endsWith('/')) {
            throw new C.Error.NotFoundError();
        }

        if (filename.indexOf('..') != -1) {
            throw new C.Error.NotFoundError();
        }

        var target = path.join(root, filename);

        fs.exists(target, function(exists) {

            if (!exists) return next();

            if (fs.lstatSync(target).isDirectory()) return next();

            res.sendfile(target);
        });
    });
};
